package top.zhangjianyong.blog.ai.client;

import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

/** OpenAI摘要生成服务 封装了调用OpenAI大模型生成文章摘要的逻辑 */
@Slf4j
@Component
public class OpenAiClient {

  private final ChatModel chatModel;

  @Autowired
  public OpenAiClient(ChatModel chatModel) {
    this.chatModel = chatModel;
  }

  /**
   * 流式输出的chat方法，返回AI生成内容的字符串流
   *
   * @param messages 用户输入内容
   * @return Flux<String> 流式输出的AI回复
   */
  public Flux<String> chat(List<Message> messages) {

    OpenAiChatOptions options =
        OpenAiChatOptions.builder()
            // .model("gpt-4o-mini") // 这里指定模型
            .temperature(0.7)
            .build();
    Prompt chatPrompt = new Prompt(messages, options);
    // 返回流式字符串输出
    return this.chatModel.stream(chatPrompt)
        .map(
            response -> {
              if (response.getResults() == null || response.getResults().isEmpty()) {
                log.debug("data: [{}]", "");
                return "";
              }
              var output = response.getResults().get(0).getOutput();
              if (output == null || output.getText() == null) {
                log.debug("data: [{}]", "");
                return "";
              }
              log.debug("data: [{}]", output.getText());
              return output.getText();
            });
  }
}
